<html>

<head>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <META HTTP-EQUIV="pragma" content="no-cache">
    <META HTTP-EQUIV="Cache-Control" content="no-store, must-revalidate">
    <META HTTP-EQUIV="expires" content="0">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>首页</title>

    <link href="https://libs.cdnjs.net/twitter-bootstrap/4.3.1/css/bootstrap.css" rel="stylesheet">
    <link href="//at.alicdn.com/t/font_1494741_ocv8339blrb.css" rel="stylesheet">
    <link href="__PUBLIC__/chat/css/main.css" rel="stylesheet">


    <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://libs.cdnjs.net/twitter-bootstrap/4.3.1/js/bootstrap.js"></script>
    <script src="https://libs.cdnjs.net/twitter-bootstrap/3.2.0/js/alert.js"></script>
    <script type="text/javascript" src="__PUBLIC__/vendor/layer/layer.js"></script>
    <script type="text/javascript" src="__PUBLIC__/chat/js/main.js"></script>



    <body onload="connect();">
        <div class="home">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-md-3 col-sm-5 col-12">
                        <div class="row">

                            {include file="/index/left" /}
                            <!--  -->
                            {include file="/index/center" /}
                        </div>
                    </div>
                    <!-- <iframe src="http://www.hrblkk.com" frameborder="0" width="700px" height="500px"></iframe> -->
                    <!-- <b style="color: ##795548;font-style: oblique;font-size: 39px;text-shadow: 5px 5px 5px #000;">能优化的地方太多了</b> -->

                    <!--  -->
                    {include file="/index/right" /}
                </div>
            </div>
        </div>

        <div id="chart_demo" class="hidden">
            <div class="medias flr">
                <div class="medias-left">
                    <div class="medias-head"></div>
                </div>
                <div class="medias-body">
                    <h4 class="medias-heading"></h4>
                    <div class="medias-text">
                        <div class="triangle"></div>
                        <div class="medias-content"></div>
                    </div>
                </div>
            </div>
        </div>



        <script>
            // 如果浏览器不支持websocket，会使用这个flash自动模拟websocket协议，此过程对开发者透明
            WEB_SOCKET_SWF_LOCATION = "__PUBLIC__/chat/swf/WebSocketMain.swf";
            // 开启flash的websocket debug
            WEB_SOCKET_DEBUG = true;

            var ws, name, client_list = {};

            // 连接服务端
            function connect() {
                //激活日历程序
                onloads();

                // 创建websocket
                ws = new WebSocket("ws://" + document.domain + ":7272");
                // 当socket连接打开时，输入用户名
                ws.onopen = onopen;
                // 当有消息时根据消息类型显示不同信息
                ws.onmessage = onmessage;
                ws.onclose = function() {
                    console.log("连接关闭，定时重连");
                    connect();
                };
                ws.onerror = function() {
                    console.log("出现错误");
                };
            }
            // 连接建立时发送登录信息
            function onopen() {
                var name = "{:getSessInfo('nickname')}";
                var user_id = "{:getSessInfo('id')}";

                // 登录
                var login_data = {
                    type: "login_client",
                    client_name: name.replace(/"/g, '\\"'),
                    user_id: user_id
                };
                console.log("websocket握手成功，发送登录数据:" + JSON.stringify(login_data));
                ws.send(JSON.stringify(login_data));

                /**测试链接发送消息*/
                var data = {
                    type: 'say_client',
                    room_id: 0,
                    user_id: 0,
                    other_id: 0,
                    ide: 0,
                    content: '链接测试'
                }
                ws.send(JSON.stringify(data))

            }


            // 服务端发来消息时
            function onmessage(e) {
                // console.log(e.data);
                var data = eval("(" + e.data + ")");
                switch (data['type']) {
                    // 服务端ping客户端
                    case 'ping':
                        //心跳提示
                        var data = {
                            type: 'pong'
                        }
                        ws.send(JSON.stringify(data));
                        break;
                        // 登录 更新用户列表
                    case 'all':
                        checkGroup(data);
                        break;
                    case 'login_client':
                        console.log(data['client_name'] + "登录成功");
                        break;
                        // 发言
                    case 'say_client':
                        // console.log('say', data);
                        if (!data.room_id && !data.user_id) {
                            return;
                        }
                        var active = $('.home .center .list li.active a');
                        if ($(active).data('id') == data['room_id']) {
                            //只在激活也显示
                            say(data['from_client_id'], data['from_client_name'], data['content'], data['time'], 2, data['ide']);
                            //更新未读消息提示
                            updataStatus(data['room_id']);
                        } else {
                            //如果不是激活页 
                            ideun(data['room_id']);
                        }
                        //更新列表描述
                        if (data['is_show'] == "{:getSessInfo('id')}") {
                            updataMsg(data['room_id'], data['content'], data['other_id'], data['time'], data['from_client_name'], "{:getSessInfo('id')}", data['ide'], 'is_u_show');
                        } else {
                            updataMsg(data['room_id'], data['content'], "{:getSessInfo('id')}", data['time'], data['from_client_name'], data['other_id'], data['ide'], 'is_o_show');
                        }
                        //更新网站title
                        document.title = '有新消息...';
                        //弹窗提示
                        alertShow(data['from_client_name'], data['content']);
                        break;
                        // 自己发言
                    case 'say_client_mi':
                        say(data['from_client_id'], data['from_client_name'], data['content'], data['time'], 1, data['ide']);
                        //更新列表描述
                        if (data['is_show'] == "{:getSessInfo('id')}") {
                            updataMsg(data['room_id'], data['content'], data['other_id'], data['time'], data['from_client_name'], "{:getSessInfo('id')}", data['ide'], 'is_u_show');
                        } else {
                            updataMsg(data['room_id'], data['content'], "{:getSessInfo('id')}", data['time'], data['from_client_name'], data['other_id'], data['ide'], 'is_o_show');
                        }
                        break;
                    case 'times':
                        var active = $('.home .center .list li.active a');
                        if ($(active).data('id') == data['room_id']) {
                            $('#chat_data').append('<div class="message"><span>' + data['content'] + '</span></div>');
                        }
                        break;
                        //群聊
                    case 'say':
                        var active = $('.home .center .list li.active a');
                        if ($(active).data('id') == data['room_id']) {
                            var user_id = "{:getSessInfo('id')}";
                            if (data['user_id'] == user_id) {
                                say(data['from_client_id'], data['from_client_name'], data['content'], data['time'], 1, data['ide']);
                            } else {
                                say(data['from_client_id'], data['from_client_name'], data['content'], data['time'], 2, data['ide']);
                            }
                        }
                        var dates = new Date();
                        $('.room' + data.room_id + " .msg").text(data.content);
                        $('.room' + data.room_id + " .time").text(dates.getHours() + ":" + dates.getMinutes());
                        break;
                    case 'add_friend':
                        $('.home .contacts .ide').show().addClass('active');
                        $('.list2 .msg2 .ide').show().addClass('active');
                        break;
                    case 'get_friend':
                        getFriend();
                        break;
                    case 'add_group':
                        $('.home .left .message').addClass('active');
                        $('.home .left .contacts').removeClass('active');
                        $('.home .left .user').removeClass('active');
                        $('.home .center .list2').addClass('hidden');
                        $('.home .center .list').removeClass('hidden');
                        $('.home .center .list0').addClass('hidden');
                        $('.home .right .box2').addClass('hidden');
                        $('.home .right .box').addClass('hidden');
                        getGroup();
                        checkGroup(data);
                        cutoverActive($('.home .center .list .room' + data['room_id'] + ' a'));
                        break;
                        // 用户退出 更新用户列表
                    case 'logout':
                        // say(data['from_client_id'], data['from_client_name'], data['from_client_name'] + ' 退出了', data['time'], data['ide']);
                        delete client_list[data['from_client_id']];
                }
            }

            // 发言 客户端地址 发送者名称 发送内容 时间 类型 标签 是否后追加
            function say(from_client_id, from_client_name, content, time, type, head = 'A', app = 'append') {
                if (type == 1) { //自己发言
                    $('#chart_demo .medias').removeClass('fll').addClass('flr');
                } else {
                    $('#chart_demo .medias').removeClass('flr').addClass('fll');
                }
                $('#chart_demo .medias-head').text(head);
                $('#chart_demo .medias-heading').text(from_client_name);
                // content = content.replace(/\n/g, "<br>");
                $('#chart_demo .medias-content').html(content);
                var html = $('#chart_demo').html();
                if (app == 'append') {
                    $('#chat_data').append(html);
                } else {
                    $('#chat_data').prepend(html);
                }
                ChangeScrollHeight(9999999);
            }

            /**
             * 标记未读
             */
            function ideun(id) {
                $('.room' + id).find('.ide').addClass('show');
                if ($('.home .left .message.active').length <= 0) {
                    $('.home .left .message').find('.ide').show();
                }
            }

            /**
             * 切换会话激活状态并加载历史记录
             */
            function cutoverActive(e) {
                // console.log(e);

                if ($(e).data('group') == 1) {
                    var name = "{:getSessInfo('nickname')}";
                    var user_id = "{:getSessInfo('id')}";
                    var room_id = $(e).data('id');
                    var data = {
                            type: 'login',
                            client_name: name,
                            user_id: user_id,
                            room_id: room_id
                        }
                        // console.log(data);

                    ws.send(JSON.stringify(data))
                }
                $('.list li').removeClass('active');
                $('.home .right .nickname').text($(e).find('.nick').text());
                $('.home .right .box').removeClass('hidden');
                var id = $(e).data('id');
                var user = "{$user_id}";
                $('.room' + id).addClass('active');
                $('.room' + id).find('.ide').removeClass('show');

                document.title = '首页';
                if ($('.home .center .list li a .ide.show').length <= 0) {
                    $('.home .left .message').find('.ide').hide();
                }

                $.post("{:url('getRoomsDetails')}", {
                    id
                }, function(res) {
                    if (res.code == 1 || res.data.length > 0) {
                        $('#chat_data').empty();
                        $.each(res.data, function(i, v) {
                            var type = (user == v.user_id) ? 1 : 2;

                            if (v.type == 1) {
                                $('#chat_data').prepend('<div class="message"><span>' + v.content + '</span></div>');
                            } else {
                                say('', v.user.nickname, v.content, v.created_time, type, v.user.ide, 'prepend');
                            }
                        })
                    }
                })
                ChangeScrollHeight(9999999);

            }

            /**
             * 更新未读消息状态
             */
            function updataStatus(id) {
                $.get("{:url('updateRoomsStatus')}?id=" + id, function(res) {})
            }

            /*
             *删除列表
             */
            function dellist(e) {
                var active = $('.home .center .list li.active a');
                var id = $(active).data('id');
                var user = $(active).data('user_id');
                var type = $(active).data('type');
                var group = $(active).data('group');

                layer.confirm('确认要移除聊天吗？', {
                    btn: ['确认', '取消'] //按钮
                }, function() {
                    $.post("{:url('dellist')}", {
                        id,
                        user,
                        type,
                        group
                    }, function(res) {
                        layer.msg(res.msg);
                        if (res.code == 1) {
                            $('.room' + id).remove();
                            $('.home .right .box').addClass('hidden');
                        }
                    })
                }, function() {

                });
                return false;
            }

            /**
             * 更新列表描述
             */
            function updataMsg(id, content, otherid, time, nickname, userid, ide, is_o = 'is_o_show') {
                if ($('.room' + id).length > 0) {
                    $('.room' + id + " .msg").text(content);
                    $('.room' + id + " .time").text(time);
                } else {
                    var html = '';
                    html += ' <li class="room' + id + '">';
                    html += '   <a href="###" onclick="cutoverActive(this)" data-other_id="' + otherid + '" data-id="' + id + '" data-user_id="' + userid + '" data-type="' + is_o + '">';
                    html += '        <div class="ide show"></div>';
                    html += '        <div class="head">' + ide + '</div>';
                    html += '        <div class="name">';
                    html += '            <div class="nick">' + nickname + '</div>';
                    html += '            <div class="msg">' + content + '</div>';
                    html += '        </div>';
                    html += '        <div class="time">' + time + '</div>';
                    html += '    </a>';
                    html += '</li>';
                    $('.home .center .box .list ul').prepend(html);
                }


            }

            /**
             * 检测群组是否存在或激活
             */
            function checkGroup(data) {
                console.log(data);

                if ($('.roomgroup.room' + data['room_id']).length > 0) {
                    if ($('.roomgroup.active a').data('id') != data['room_id']) {
                        $('.roomgroup.room' + data['room_id']).find('.ide').addClass('show');
                        if ($('.home .left .message.active').length <= 0) {
                            $('.home .left .message').find('.ide').show();
                        }
                    }
                } else {
                    var user_id = "{:getSessInfo('id')}";
                    if (data.allids.indexOf("," + user_id + ",") >= 0) {
                        var html = "";
                        html += '';
                        html += '<li class="room' + data.room_id + ' roomgroup">';
                        html += '   <a href="###" onclick="cutoverActive(this)" data-id="' + data.room_id + '" data-group="1">';
                        html += '       <div class="ide show"></div>';
                        html += '           <div class="head">' + data.ide + '</div>';
                        html += '               <div class="name">';
                        html += '                    <div class="nick">' + data.group_name + '</div>';
                        html += '               <div class="msg">' + data.content + '</div>';
                        html += '           </div>';
                        html += '       </a>';
                        html += '   <div class="time">' + data.time + '</div>';
                        html += '</li>';
                        $('.home .center .box .list ul').prepend(html);
                    }
                }

            }
        </script>



        <script>
            var friend;

            function addfriend(type) {
                if (type == 'group') {
                    var url = "{:url('addgroup')}";
                    var title = "创建群聊";
                } else {
                    var url = "{:url('addfriend')}";
                    var title = "添加好友";
                }

                layer.closeAll();
                width = $(window).width();
                if (width > 700) {
                    friend = layer.open({
                        type: 2,
                        title: title,
                        shadeClose: true,
                        shade: false,
                        maxmin: true, //开启最大化最小化按钮
                        area: ['893px', '600px'],
                        content: url,
                    });
                } else {
                    friend = layer.open({
                        type: 2,
                        title: title,
                        shadeClose: true,
                        shade: false,
                        maxmin: true, //开启最大化最小化按钮
                        area: ['100%', '100%'],
                        content: url,
                    });
                    $('.layui-layer').css('top', 0);
                }
                cutoverAdd();
            }

            var newfriend = "{$newfriend}";
            var newchat = "{$newchat}"
            if (newfriend > 0) {
                $('.home .contacts .ide').show().addClass('active');
                $('.list2 .msg2 .ide').show().addClass('active');
            }
            if (newchat > 0) {
                $('.home .left .message .ide').show();
            }

            //获取好友列表
            function getFriend() {
                $.get("{:url('getFriend')}", function(res) {
                    if (res) {
                        $('#lgroup').empty().html(res);
                        openMessage();
                    }
                })
            }

            //获取好友列表
            function getGroup() {
                console.log(1);

                $.get("{:url('getGroup')}", function(res) {
                    if (res) {
                        $('#qgroup').empty().html(res);
                    }
                })
            }
        </script>

    </body>

</html>